# pragma once
#include <string>
#include <vector>
#include <thread>
#include <mutex>
#include <atomic>
#include <future>
#include <queue>
#include <condition_variable>
#include <functional>

#include "DGGSDefine.hpp"

#include "DGGSFeatureLayer.hpp"

#include "IDGGSKernel.hpp"
#include "GridTIFF.hpp"

using namespace NNU::DGGS;
using namespace NNU::DGGS::Kernel;
using namespace NNU::DGGS::Feature;

_NNU_DGGS_BEGIN
namespace DGGSViewer{
    class Cell{
    public:
        std::vector<GeoCoord> m_coordinates;
        std::vector<double> values;
    };

    // 线程池类，用于多线程处理数据
    class ThreadPool {
        std::vector<std::thread> workers;
        std::queue<std::function<void()>> tasks;
        std::mutex queue_mutex;
        std::condition_variable condition;
        std::atomic<bool> stop;
    
    public:
        ThreadPool(size_t threads);
        ~ThreadPool();
        
        template<class F, class... Args>
        auto enqueue(F&& f, Args&&... args) 
            -> std::future<typename std::result_of<F(Args...)>::type>;
    };

    class DGGSVisualizer{
        void tiffHandler(const std::string& filePath);
        void jsonHandler(const std::string& filePath);
        void processTiffBatch(GridTIFF* gridTiff, const std::vector<int>& indices,
                            const DGGridBBox& gridBBox, std::vector<Cell>& result) const;
        IDGGSKernel* m_kernel = nullptr;
        
        static bool XY2Code(int x, int y, DGGSElementCode& code, const DGGridBBox& gridBBox);
        static bool Code2XY(DGGSElementCode code, int& x, int& y, DGGridBBox gridBox);
        static DGGridBBox getGridBoxFromGridTrans(GridTransform gridTrans, int gridSize);
        
        // 多线程和批处理相关
        std::unique_ptr<ThreadPool> m_threadPool;
        size_t m_batchSize = 1000; // 默认批处理大小
        std::mutex m_cellsMutex; // 保护cells向量的互斥锁

    public :
        std::vector<Cell> cells;
        DGGSElementType type;

        void loadData(const std::string& filePath);
        void loadMultipleData(const std::vector<std::string>& filePaths);
        
        // 新增方法：设置批处理大小
        void setBatchSize(size_t batchSize) { m_batchSize = batchSize; }
    };
}
_NNU_DGGS_END